#include "chunk.h"

Chunk::Chunk()
{
    no_of_voxels=0;
    x=y=z=0;
    changed=true;
}

/*
void Chunk::renderWalk(seeker &seekr){
    if(seekr.isfull()){
        for(int i=seekr.a;i<=seekr.b;i++){
            vector3<int> v=index_to_vector(i);
            vbo->addVoxel(varr[i],v.x,v.y,v.z);
        }
    }
    else if(seekr.isempty())return;
    else{
        renderWalk(*(seekr.left));
        renderWalk(*(seekr.right));
    }
}
*/

void Chunk::render(){
    if(changed){
    vbo->reset();
    //renderWalk(seek);
    for(int i=0;i<(CHUNK_SIZE * CHUNK_SIZE * CHUNK_SIZE);i++)
    {
        if(varr[i].draw())
        {
            vector3<int> v=index_to_vector(i);
            vbo->addVoxel(varr[i],v.x,v.y,v.z);
        }
    }
    changed=false;
    vbo->render();
    }
    else
        vbo->render();
}

void Chunk::setWorldCoords(uchar _x, uchar _y, uchar _z){
    x=_x;
    y=_y;
    z=_z;
}

void Chunk::initVBO(){
    vbo=new VBOManager(x,y,z);
}

voxel& Chunk::getChunkVoxel(int x, int y, int z){
    return varr[vector_to_index(x, y, z)];
}

void Chunk::addChunkVoxel(int x, int y, int z, voxel &v){
    int index=vector_to_index(x, y, z);
    // if exist, overwrite
    if(!varr[index].draw()){
        ++no_of_voxels;
        //seek.add(index);
    }
    changed=true;
    v.setDraw(true);
    //v.setWorldCoords(x, y, z);
    varr[index]=v;
}

void Chunk::removeChunkVoxel(int x, int y, int z){
    int index=vector_to_index(x, y, z);
    if(no_of_voxels>0 && varr[index].draw()){
        --no_of_voxels;
        //seek.remove(index);
    }
    changed=true;
    varr[index].setDraw(false);
}

void Chunk::setVoxelColor(int x, int y, int z, colour& c){
    vbo->setVoxelColor(x,y,z,c);
    varr[vector_to_index(x, y, z)].setColor(c);
}

bool Chunk::IsEmpty(){
    return no_of_voxels==0;
}
